import { getToken, setToken, removeToken, getTime, setTime, removeTime, getLoginInfo, setLoginInfo, removeLoginInfo } from '@/utils/auth.js'
import { login, getUserInfo } from '@/api/user'
import { getUser } from '@/api/employees'
export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {},
    time: getTime(),
    loginInfo: getLoginInfo()
  },
  mutations: {
    setToken(state, token) {
      const time = Date.now()
      state.time = time
      setTime(time)
      state.token = token
      setToken(token)
    },
    removeToken(state) {
      state.time = null
      removeTime()
      state.token = null
      removeToken()
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    reomveUserInfo(state) {
      state.userInfo = {}
    },
    setLoginInfo(state, loginInfo) {
      state.loginInfo = loginInfo
      setLoginInfo(loginInfo)
    },
    removeLoginInfo(state) {
      state.loginInfo = {}
      removeLoginInfo()
    }
  },
  actions: {
    async login(context, date) {
      // const { data: { success, data }} = await login(date)
      // if (success) context.commit('setToken', data)
      // 进过响应拦截的处理之后  这里的result实际上就是 token
      const result = await login(date)
      context.commit('setToken', result)
      context.commit('setLoginInfo', date)
    },
    async getUserInfo(context) {
      const result = await getUserInfo()
      const res = await getUser(result.userId)
      context.commit('setUserInfo', { ...result, ...res })
      return result // 这里为什么要返回 为后面埋下伏笔
    },
    logout(context) {
      context.commit('removeToken')
      context.commit('reomveUserInfo')
      context.commit('permission/setRouters', [], { root: true })
    },
    removeLoginInfo(context) {
      context.commit('removeLoginInfo')
    }
  }
}
